<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace app\shop\controller;

/**
 * Description of ReceiveCode
 *
 * @author pcy
 */
class ReceiveCode extends Controller
{
    public function index()
    {
        $code = Request::get('code');
        
        $accessToken = YangCai::getAccessToken($code);
        
        $userInfoRs = YangCai::getUserInfo($accessToken);
        
        $unitInfoRs = YangCai::getUnitInfo($accessToken);
        
        if ( !$userInfoRs['success'] )
        {
            echo '获取用户信息失败';exit;
        }
        
        if ( !$unitInfoRs['success'] )
        {
            echo '获取用户单位信息失败';exit;
        }
        
        $userAttributes = $userInfoRs['rows'];
        var_dump($userAttributes);exit;
//        $userInfo = YcUser::model()->find("usercode='{$userAttributes['usercode']}'");
        
        if ( empty( $userInfo ) )
        {
            $userInfo = new YcUser();
            
            $userInfo->attributes = $userAttributes;
            
            $userInfo->save();
        }
        else if ( $userInfo['updatetime'] < $userAttributes['updatetime'] )
        {
            $userInfo->attributes = $userAttributes;
            
            $userInfo->save();
        }
        
        $unitAttributes = $unitInfoRs['rows'];

        $unitInfo = YcUnit::model()->find("unitcode='{$unitAttributes['unitcode']}'");
        
        if ( empty( $unitInfo ) )//本地不存在
        {
            $unitInfo = new YcUnit();
            
            $unitInfo->attributes = $unitAttributes;
            
            $unitInfo->save();
        }
        else if ( $unitInfo['updatedat'] < $unitAttributes['updatedat'] )//本地数据不是最新
        {
            $unitInfo->attributes = $unitAttributes;
            
            $unitInfo->save();
        }
        
        $authArr = array(//用户类型和用户唯一编号
            2,
            $userInfo['usercode']
        );
        
        $authStr = $this->authEnCode($authArr);
        
        Func::setCookie('auth', $authStr);//把登录状态写入cookie
    }
}
